<template>
  <el-dialog
    :close-on-click-modal="false"
    :top="isMore ? '7vh' : '15vh'"
    :width="isMore ? '60%' : '60%'"
    :title="title"
    :visible.sync="visible"
    :before-close="close"
    lock-scroll
    append-to-body
  >
    <el-form
      status-icon
      :rules="rules"
      :model="datas"
      @keyup.enter.native="save"
      ref="editForm"
      style="position: relative"
    >
      <el-row :gutter="10">
        <el-col :span="23">
          <!-- 批量添加人员 -->
          <el-form-item v-if="isMore" prop="name" label label-width="0">
            <!-- <el-select
              v-model="datas.name"
              collapse-tags
              placeholder="请输入关键字搜索"
              filterable
              multiple
              remote
              :remote-method="(val)=>{getUserList(val,true)}"
              :loading="loading"
              style="width: 100%;"
            >
              <el-option
                v-for="(item,index) in userDatas"
                :key="item.id+'qww'+index"
                :label="item.realname"
                :value="item.realname"
              ></el-option>
            </el-select>-->
            <div class="name-tag-title">已选人员如下</div>
            <div class="name-tag-box">
              <el-tag
                size="mini"
                v-for="item in checkedUsers"
                :key="item"
                style="margin-left: 10px"
                >{{ item }}</el-tag
              >
            </div>
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange"
              >全选</el-checkbox
            >
            <el-checkbox-group
              v-model="checkedUsers"
              @change="handleCheckedUsersChange"
              style="max-height: 39vh; overflow: auto"
            >
              <el-checkbox
                v-for="user in userDatas"
                :label="user.realname"
                :key="user.id"
                >{{ user.realname }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-col>

        <!-- 单个添加人员 -->
        <el-col :span="12">
          <el-form-item
            v-if="!isMore"
            prop="name"
            label="人员"
            :label-width="baseStyle.width"
          >
            <el-select
              v-if="title != '编辑人员'"
              v-model="datas.name"
              collapse-tags
              placeholder="请输入关键字搜索"
              style="width: 100%"
              filterable
              remote
              :remote-method="
                (val) => {
                  getUserList(val, false);
                }
              "
              :loading="loading"
            >
              <el-option
                v-for="(item, index) in userDatas"
                :key="item.id + 'qww' + index"
                :label="item.realname"
                :value="item.realname"
              ></el-option>
            </el-select>
            <el-input
              v-else
              readonly
              v-model="datas.name"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="!isMore"
            prop="kp"
            label="类型"
            :label-width="baseStyle.width"
          >
            <!-- <el-switch v-model="datas.kp"></el-switch> -->
            <el-select
              v-model="datas.kp"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in classData"
                :key="item.id + index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="!isMore"
            prop="is_outer"
            label="是否跨部门考核"
            :label-width="baseStyle.width"
          >
            <!-- <el-switch v-model="datas.kp"></el-switch> -->
            <el-select
              v-model="datas.is_outer"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="!isMore"
            prop="is_reiviewed"
            label="是否参与考核"
            :label-width="baseStyle.width"
          >
            <el-select
              v-model="datas.is_reiviewed"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="!isMore"
            prop="orgname"
            label="所属部门"
            :label-width="baseStyle.width"
          >
            <SearchParts :orgname="datas.orgname" @chosePart="chosepart" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button :type="'primary'" :loading="saveLoading" @click.native="save()"
        >保存</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { Message } from "element-ui";
import API from "@apis/newProject";
import SearchParts from "@light-app/views/searchParts";

export default {
  name: "ClassicForm",
  props: {
    visible: Boolean,
    isMore: Boolean,
    baseStyle: Object,
    title: String,
    datas: {
      type: Object,
      default: function () {
        return { name: "", kp: "", is_outer: 0, is_reiviewed: 1 };
      },
    },
    classData: Array,
    saveForm: Function,
  },
  data() {
    const rules = this.getRules();
    return {
      saveLoading: false,
      loading: false,
      rules,
      userDatas: [],
      formDate: {},
      userPage: 1,

      checkAll: false,
      isIndeterminate: true,
      checkedUsers: [],
    };
  },
  components: {
    SearchParts,
  },
  computed: {},
  created() {
    if (this.isMore) {
      this.getUserList("", true);
    }
  },
  methods: {
    async getUserList(word = "", isMore) {
      if (word == "" && !isMore) {
        return;
      }
      let parmars = {};
      if (isMore) {
        parmars = {
          page: this.userPage,
          pageSize: 1000,
          keyword: word,
        };
      } else {
        parmars = {
          page: this.userPage,
          pageSize: 50,
          keyword: word,
        };
      }
      this.loading = true;
      await API.getUserList(parmars)
        .then((res) => {
          let oldIDs = this.userDatas && this.userDatas.map((item) => item.id);
          let newData = [...res.data, ...this.userDatas];
          newData.forEach((item) => {
            if (oldIDs.indexOf(item.id) < 0) {
              this.userDatas.unshift(item);
            }
          });
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
          this.$message.error(err.message);
        });
    },
    cancel() {
      this.saveLoading = false;
      this.$emit("update:visible", false);
      this.$refs.editForm.resetFields();
    },
    close() {
      this.cancel();
    },
    save() {
      this.$refs.editForm.validate((valid) => {
        // console.log(this.datas, "datas");
        if (valid) {
          let datas = [];
          if (this.userDatas && this.userDatas.length > 0) {
            datas = this.userDatas.filter(
              (item) => item.realname == this.datas.name
            );
          } else {
            datas = [{ id: this.datas.uid }];
          }
          this.saveLoading = true;
          this.$emit("saveForm", { uid: datas[0].id, ...this.datas });
          // this.cancel();
        } else {
          return false;
        }
      });
    },
    getRules() {
      return {
        name: [
          {
            validator: (rule, value, callback) => {
              if (!this.datas.name) {
                callback(new Error(`请选择管理员`));
                return;
              }
              if (this.datas.name.length < 1) {
                callback(new Error(`请选择管理员`));
                return;
              }
              callback();
            },
            trigger: "blur",
          },
        ],
      };
    },

    handleCheckAllChange(val) {
      let allUsers = this.userDatas.map((item) => {
        return item.realname;
      });
      // console.log(val, allUsers, "allUsers");
      this.checkedUsers = val ? allUsers : [];
      this.isIndeterminate = false;
    },
    handleCheckedUsersChange(value) {
      let userSelect = [];
      value.map((val) => {
        this.userDatas.filter((user) => {
          return val === user.realname ? userSelect.push({ ...user }) : "";
        });
      });
      console.log(userSelect, "userSelect");
      console.log(value, "value");
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.userDatas.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.userDatas.length;
      this.checkedUsers = [...value];
    },

    chosepart(val) {
      this.datas.orgname = val.label;
      this.datas.orgid = val.id;
      // console.log("val：", val);
    },
  },
};
</script>
<style lang="scss" scoped>
.name-tag-title {
  position: absolute;
  top: -40px;
}
.name-tag-box {
  border: 1px solid #ccc;
  min-height: 40px;
  max-height: 70px;
  overflow: auto;
  line-height: 30px;
}
</style>